package com.cctc.rds.raft.sdk.client.rpc.log;

import com.cctc.rds.nrpc.api.exception.RpcIOException;
import com.cctc.rds.nrpc.api.rpc.RpcRequest;
import com.cctc.rds.nrpc.api.rpc.RpcResponse;
import com.cctc.rds.nrpc.core.client.NettyRpcClient;
import com.cctc.rds.raft.core.rpc.log.LogRpc;
import com.cctc.rds.raft.core.rpc.log.LogRpcRequest;
import com.cctc.rds.raft.core.rpc.log.LogRpcResponse;

public class LogRpcRequestImpl implements LogRpc {
    private NettyRpcClient client;

    public LogRpcRequestImpl(NettyRpcClient client) {
        this.client = client;
    }

    @Override
    public LogRpcResponse append(LogRpcRequest request) {
        RpcRequest rpcRequest = RpcRequest.builder()
                .interfaces(LogRpc.class)
                .methodName("append")
                .parameterTypes(new Class<?>[]{LogRpcRequest.class})
                .arguments(new Object[]{request})
                .build();
        try {
            RpcResponse rpcResponse = client.remoteInvoke(rpcRequest);
            if (rpcResponse.getException() != null) {
                throw new RuntimeException(rpcResponse.getException());
            }
            return (LogRpcResponse) rpcResponse.getResult();
        } catch (RpcIOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean commit(long index, long term) {
        RpcRequest rpcRequest = RpcRequest.builder()
                .interfaces(LogRpc.class)
                .methodName("commit")
                .parameterTypes(new Class<?>[]{Long.class, Long.class})
                .arguments(new Object[]{index, term})
                .build();
        try {
            RpcResponse rpcResponse = client.remoteInvoke(rpcRequest);
            if (rpcResponse.getException() != null) {
                throw new RuntimeException(rpcResponse.getException());
            }
            return (Boolean) rpcResponse.getResult();
        } catch (RpcIOException e) {
            throw new RuntimeException(e);
        }
    }
}
